import logging
from forum.models import Attachments, TopicThumb, TopicFollow, Comment, Topic
from user_app.models import AccountFollow, ModuleType, AccountInfo
from django.db import transaction

logger = logging.getLogger(__name__)
error_logger = logging.getLogger("error")


def get_img_attachments(topic_id, suffix=None, category=0):
    """
        获取指定Topic下面的图片
    """
    if suffix is None:
        suffix = ['JPEG', 'JPG', 'PNG']
    query = Attachments.objects.filter(topic_id=topic_id, suffix__in=suffix, category=category).values_list("file_url", flat=True)
    return list(query)


def get_video_attachments(topic_id, suffix=None, category=0):
    """
        获取指定Topic下面的视频
    """
    if suffix is None:
        suffix = ['MP4']
    query = Attachments.objects.filter(topic_id=topic_id, suffix__in=suffix, category=category).values_list("file_url", flat=True)
    return list(query)


def get_account_is_follow(created_by_id, follow_account_id):
    return AccountFollow.objects.filter(created_by_id=created_by_id, follow_account_id=follow_account_id).exists()


def delete_topic_common(topic_id):
    """
        删除帖子通用接口
    """
    with transaction.atomic():
        save_id = transaction.savepoint()
        try:
            TopicThumb.objects.filter(topic_id=topic_id, category=0).delete()
            TopicFollow.objects.filter(follow_topic_id=topic_id, category=0).delete()
            Attachments.objects.filter(topic_id=topic_id, category=0).delete()
            Comment.objects.filter(topic_id=topic_id, category=0).delete()
            Topic.objects.filter(id=topic_id).delete()
        except Exception as e:
            error_logger.exception("delete_topic have a  error ---->%s" % e.__str__())
            transaction.savepoint_rollback(save_id)
            return False
        transaction.savepoint_commit(save_id)
        return True


def module_list_to_name(module_list):
    """
        数字的module_list转换成中文权限名
    """
    module_type_list = ModuleType.objects.all().values_list("id", "module_name")
    module_dict = {}
    for item in module_type_list:
        module_dict[item[0]] = item[1]
    result_list = []
    for num in eval(module_list):
        result_list.append(module_dict.get(num, ""))
    return result_list


def check_allow_post(account_id):
    """
        检查是否被禁言
    """
    if AccountInfo.objects.get(id=account_id).is_allow_post == 1:
        return True, '您已被禁言，无法发布'
    else:
        return False, ''
